package com.yang.designmode.prototype;

import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class UserDeepTypeSerializable implements Cloneable,Serializable {
    private String name;
    private int age;
    private Date birthday;


    public UserDeepTypeSerializable() {
    }

    public UserDeepTypeSerializable(String name, int age, Date birthday) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String toString() {
        return "User [name=" + name + ", age=" + age + ", birthday=" + birthday + "]";
    }



    @Override
    public UserDeepTypeSerializable clone() {
        try {
            UserDeepTypeSerializable clone = (UserDeepTypeSerializable) super.clone();
            // 实现克隆对象属性的深拷贝
            clone.birthday = (Date) clone.birthday.clone();
            return clone;
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }

    public static void main(String[] args) throws Exception {
        UserDeepTypeSerializable user = new UserDeepTypeSerializable();
        user.setName("yang");
        user.setAge(18);
        LocalDate localDate = LocalDate.parse("2000-01-01", DateTimeFormatter.ISO_LOCAL_DATE);
        user.setBirthday(java.sql.Date.valueOf(localDate));

        System.out.println("源对象：" + user);

        //序列化
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(user);

        //反序列化
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        UserDeepTypeSerializable user_1 = (UserDeepTypeSerializable)ois.readObject();
        System.out.println("序列化深克隆对象："+user_1);

        // 验证不共享 birthday 的行为
        Date userBirthday = user.getBirthday();
        userBirthday.setTime(userBirthday.getTime() + 1000 * 60 * 60 * 24 * 1); // 加一天
        System.out.println("验证不共享 birthday 的行为");
        System.out.println("源对象：" + user);
        System.out.println("深克隆对象：" + user_1);
    }
}
